//
//  InterfaceController.m
//  WatchApp Extension
//
//  Created by 王胜利 on 2019/3/15.
//  Copyright © 2019 wsl. All rights reserved.
//

#import "InterfaceController.h"
#import "WalletRow.h"
#import "WalletDetailController.h"
#import "WatchWCSessionManager.h"
#import "CoreDataManager.h"
#import "Wallet+CoreDataClass.h"
#import "Wallet+CoreDataProperties.h"
#import "WKInterfaceImage+WKImageUrl.h"

@interface InterfaceController () <WatchWCSessionManagerDelegate>

@property (weak, nonatomic) IBOutlet WKInterfaceGroup *emptyGroup;
//钱包列表
@property (weak, nonatomic) IBOutlet WKInterfaceTable *table;
@property (strong, nonatomic) NSMutableArray *wallets;

@end

@implementation InterfaceController

//init和awakeWithContext:方法是用来加载页面所必须的数据和初始化页面配置的。 而不要在willActivate方法中去初始化页面配置, 但它可以做一些页面更新的事情。
//willActivate:程序激活
//didAppear: 页面已经显
//willDisappear: 页面将要消失
//didDeactivate: 这个方法与willActivate是相反的, 页面失活。它需要注意的是, 当此方法被调用时Controller已经失活了, 且不在安全了, 所以不要再进行页面上的更新等操作了。但它负责一些像NSTimer停用之类的处理是最合适不过了。

// WatchOS控制器生命周期
//当你进入一个页面时, 设备会经历init->awakeWithContext->willActivate->didAppear。
//当你退出当前页面时, 设备会经历willDisappear->didDeactivate->deinit。
//再举个例子, 当你进入一个页面时, 设备会经历init->awakeWithContext->willActivate->didAppear。然后停止所有用户交互使其进入失活状态, 设备会经历didDeactivate。直到你再次与其交互, 设备会经历willActivate。所以, 这才是它们本质的区别。


- (void)awakeWithContext:(id)context {
    [super awakeWithContext:context];
    [[WatchWCSessionManager sharedInstance] startSession];
    [WatchWCSessionManager sharedInstance].delegate = self;
    [self reloadData];
}

- (void)willActivate {
    // This method is called when watch view controller is about to be visible to user
    [super willActivate];
}

- (void)didDeactivate {
    // This method is called when watch view controller is no longer visible
    [super didDeactivate];
}

- (void)didAppear{
    [super didAppear];
    if (kCoreDataManager.isUpdate) {
        [self reloadData];
        kCoreDataManager.isUpdate = false;
    }
    
    NSDictionary *msg = [self dictionaryResult:@"0" withMsg:@"WatchInterface didAppear"];
    [[WatchWCSessionManager sharedInstance] sendMsgToPhone:msg];
    
}

//生成回包数据
- (NSDictionary*)dictionaryResult:(NSString*)strResult withMsg:(NSString*)strMsg {
    NSDictionary *result = @{
                             @"result": strResult,
                             @"msg": strMsg,
                             };
    return result;
}

- (void)reloadData{
    NSFetchRequest *request = [Wallet fetchRequest];
    NSArray<Wallet*> *arr = [kCoreDataManager.persistentContainer.viewContext executeFetchRequest:request error:nil];
    if (arr.count == 0) {
        [self.emptyGroup setHidden:false];
        [self.table setHidden:true];
        return;
    }
    [self.emptyGroup setHidden:true];
    [self.table setHidden:false];
    self.wallets = arr.mutableCopy;
    [self.table setNumberOfRows:self.wallets.count withRowType:@"WalletRow"];
    
    for (int i = 0; i < self.wallets.count; i++) {
        Wallet *obj = self.wallets[i];
        WalletRow *cell = [self.table rowControllerAtIndex:i];
        if ([obj.avatar isEqualToString:@""]) {
            [cell.headImage setImageNamed:@"headImg"];
        } else {
            [cell.headImage wkSetImageUrl:obj.avatar];
        }
        
        if (obj.addr.length >= 16) {
            cell.subName.text = [obj.addr stringByReplacingCharactersInRange:NSMakeRange(6, obj.addr.length-10) withString:@"****"];
        }
        [cell.name setText:obj.name];
        [cell.chainTypeLabel setText:obj.strChain];
    }
}

- (void)table:(WKInterfaceTable *)table didSelectRowAtIndex:(NSInteger)rowIndex{
    Wallet *dict = self.wallets[rowIndex];
    [self pushControllerWithName:@"WalletDetailController" context:dict];
}

// MARK: WatchWCSessionManagerDelegate
/// apple watch 收到消息并回复
- (void)receiveMessage:(NSDictionary<NSString *,id> *)message replyHandler:(void (^)(NSDictionary<NSString *,id> *))replyHandler {
    
    NSString *msgType = message[@"type"];
    if ([msgType isEqualToString:@"saveWallet"]) {
        [self saveWalletWithMessage:message replyHandler:replyHandler];
    }else if ([msgType isEqualToString:@"readWallet"]){
        [self readWalletWithMessage:message replyHandler:replyHandler];
    }else if ([msgType isEqualToString:@"deleteWallet"]){
        [self deleteWalletWithMessage:message replyHandler:replyHandler];
    }else if([msgType isEqualToString:@"getWatchInfo"]){
        [self getWatchInfoReplyHandler:replyHandler];
    }else if ([msgType isEqualToString:@"changeWalletName"]){
        [self changeWalletNameWithMessage:message replyHandler:replyHandler];
    }else if ([msgType isEqualToString:@"changeWalletHeadImg"]){
        [self changeWalletHeadImgWithMessage:message replyHandler:replyHandler];
    }else{
        NSDictionary *result = [self dictionaryResult:@"0" withMsg:@"Watch暂不支持改功能"];
        if (replyHandler) replyHandler(result);
    }
}

/// MARK: 消息的处理回复
- (void)saveWalletWithMessage:(nonnull NSDictionary<NSString *,id> *)message replyHandler:(nonnull void (^)(NSDictionary<NSString *,id> * _Nonnull))replyHandler{
    
    NSFetchRequest *request = [Wallet fetchRequest];
    NSDictionary *content = message[@"content"];
    //2.创建查询谓词（查询条件）
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"addr == %@",content[@"addr"]];
    //3.给查询请求设置谓词
    request.predicate = predicate;
    //4.查询数据
    NSArray<Wallet*> *arr = [kCoreDataManager.persistentContainer.viewContext executeFetchRequest:request error:nil];
    
    if (arr.count > 0) {
        NSDictionary *result = [self dictionaryResult:@"0" withMsg:@"钱包已存在"];
        if (replyHandler) replyHandler(result);
        return;
    }
    
    
    WKAlertAction *action1 = [WKAlertAction actionWithTitle:@"取消" style:WKAlertActionStyleCancel handler:^{
        NSDictionary *result = [self dictionaryResult:@"0" withMsg:@"Watch取消存储"];
        if (replyHandler) replyHandler(result);
    }];
    
    WKAlertAction *action2 = [WKAlertAction actionWithTitle:@"保存" style:WKAlertActionStyleDefault handler:^{
        Wallet *wallet = [NSEntityDescription insertNewObjectForEntityForName:@"Wallet" inManagedObjectContext:kCoreDataManager.persistentContainer.viewContext];
        NSDictionary *content = message[@"content"];
        //赋值
        wallet.name = content[@"name"];
        wallet.avatar = content[@"avatar"];
        wallet.chainId = content[@"chainId"];
        wallet.addr = content[@"addr"];
        wallet.privKey = content[@"privkey"];
        wallet.account = content[@"account"];
        wallet.strChain = content[@"strChain"];
        //保存到数据库
        [kCoreDataManager save];
        [self reloadData];
        NSDictionary *result = [self dictionaryResult:@"1" withMsg:@"保存成功"];
        
        if (replyHandler) replyHandler(result);
    }];
    NSString *strAddr = content[@"addr"];
    if (strAddr.length > 16) {
        strAddr = [strAddr stringByReplacingCharactersInRange:NSMakeRange(6, strAddr.length-10) withString:@"****"];
    }
    NSString *strMsg = [NSString stringWithFormat:@"%@\n%@", content[@"name"], strAddr];
    [self presentAlertControllerWithTitle:@"是否保存钱包？" message:strMsg preferredStyle:WKAlertControllerStyleActionSheet actions:@[action1,action2]];
    
    
}

- (void)readWalletWithMessage:(nonnull NSDictionary<NSString *,id> *)message replyHandler:(nonnull void (^)(NSDictionary<NSString *,id> * _Nonnull))replyHandler{
    NSDictionary *content = message[@"content"];
    WKAlertAction *action1 = [WKAlertAction actionWithTitle:@"取消" style:WKAlertActionStyleCancel handler:^{
        NSDictionary *result = [self dictionaryResult:@"0" withMsg:@"Watch拒绝读取"];
        if (replyHandler) replyHandler(result);
    }];
    
    WKAlertAction *action2 = [WKAlertAction actionWithTitle:@"允许" style:WKAlertActionStyleDestructive handler:^{
        NSFetchRequest *request = [Wallet fetchRequest];
        
        //2.创建查询谓词（查询条件）
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"addr == %@",content[@"addr"]];
        //3.给查询请求设置谓词
        request.predicate = predicate;
        //4.查询数据
        NSArray<Wallet*> *arr = [kCoreDataManager.persistentContainer.viewContext executeFetchRequest:request error:nil];
        
        if (arr.count > 0) {
            NSDictionary *data = @{
                                   @"name":arr.firstObject.name,
                                   @"avatar":arr.firstObject.avatar,
                                   @"chainId":arr.firstObject.chainId,
                                   @"addr":arr.firstObject.addr,
                                   @"privkey":arr.firstObject.privKey,
                                   @"account":arr.firstObject.account
                                   };
            
            NSDictionary *result = @{
                                     @"result":@"1",
                                     @"msg":@"保存成功",
                                     @"data":data
                                     };
            
            if (replyHandler) replyHandler(result);
        }else{
            NSDictionary *result = [self dictionaryResult:@"0" withMsg:@"Watch中没有此钱包信息"];
            if (replyHandler) replyHandler(result);
        }
    }];
    
    NSString *strAddr = content[@"addr"];
    if (strAddr.length > 16) {
        strAddr = [strAddr stringByReplacingCharactersInRange:NSMakeRange(6, strAddr.length-10) withString:@"****"];
    }
    NSString *msg = [NSString stringWithFormat:@"是否允许请求读取钱包\n%@私钥信息", strAddr];
    
    [self presentAlertControllerWithTitle:nil message:msg preferredStyle:WKAlertControllerStyleSideBySideButtonsAlert actions:@[action1,action2]];
}

- (void)deleteWalletWithMessage:(nonnull NSDictionary<NSString *,id> *)message replyHandler:(nonnull void (^)(NSDictionary<NSString *,id> * _Nonnull))replyHandler{
    NSFetchRequest *request = [Wallet fetchRequest];
    NSDictionary *content = message[@"content"];
    //2.创建查询谓词（查询条件）
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"addr == %@",content[@"addr"]];
    //3.给查询请求设置谓词
    request.predicate = predicate;
    //4.查询数据
    NSArray<Wallet*> *arr = [kCoreDataManager.persistentContainer.viewContext executeFetchRequest:request error:nil];
    
    if (arr.count >= 0) {
        // 删除钱包
        for (Wallet *wallet in arr) {
            [kCoreDataManager.persistentContainer.viewContext deleteObject:wallet];
        }
        [kCoreDataManager save];
        [self reloadData];
        NSDictionary *result = [self dictionaryResult:@"1" withMsg:@"钱包已删除"];
        if (replyHandler) replyHandler(result);
       
//        删除加一个刷新通知
        NSDictionary *msg = [self dictionaryResult:@"1" withMsg:@"deleteWallet Message"];
        if ([WatchWCSessionManager sharedInstance].session.isReachable){
            [[WatchWCSessionManager sharedInstance] sendMsgToPhone:msg];
        }else{
            NSLog(@"sendError:%@", @"请先开启此应用Apple客户端");
        }
        
        return;
    }else{
        // 不存在此钱包
        NSDictionary *result = [self dictionaryResult:@"0" withMsg:@"钱包不存在"];
        if (replyHandler) replyHandler(result);
    }
    
}

// 获取watch信息
- (void)getWatchInfoReplyHandler:(nonnull void (^)(NSDictionary<NSString *,id> * _Nonnull))replyHandler {
    // 1.获取watch设备信息
    WKInterfaceDevice *device = [WKInterfaceDevice currentDevice];
    NSMutableDictionary *infoDic = [[NSMutableDictionary alloc] init];
    [infoDic setObject:@"1" forKey:@"result"];
    [infoDic setObject:device.name forKey:@"name"];
    [infoDic setObject:device.systemName forKey:@"systemName"];
    [infoDic setObject:device.systemVersion forKey:@"systemVersion"];
    [device setBatteryMonitoringEnabled:true];
    [infoDic setObject:@(device.batteryLevel) forKey:@"batteryLevel"];
    
    // 2.获取watch中钱包信息
    NSFetchRequest *request = [Wallet fetchRequest];
    NSMutableArray *walletListArray = [NSMutableArray arrayWithCapacity:0];
    NSArray<Wallet*> *arr = [kCoreDataManager.persistentContainer.viewContext executeFetchRequest:request error:nil];
    for (Wallet *wallet in arr) {
        NSDictionary *dataDic = @{
                                  @"name":wallet.name,
                                  @"avatar":wallet.avatar==nil ? @"" : wallet.avatar,
                                  @"chainId":wallet.chainId,
                                  @"addr":wallet.addr,
                                  @"privkey":wallet.privKey,
                                  @"account":wallet.account,
                                  };
        [walletListArray addObject:dataDic];
    }
    
    // 3.组合数据返回
    NSDictionary *result = @{
                             @"result":@"1",
                             @"msg":@"保存成功",
                             @"walletData":walletListArray,
                             @"watchInfo":infoDic
                             };
    
    if (replyHandler) replyHandler(result);
}

// 更改钱包的名字
- (void)changeWalletNameWithMessage:(nonnull NSDictionary<NSString *,id> *)message replyHandler:(nonnull void (^)(NSDictionary<NSString *,id> * _Nonnull))replyHandler{
    NSFetchRequest *request = [Wallet fetchRequest];
    NSDictionary *content = message[@"content"];
    //2.创建查询谓词（查询条件）
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"addr == %@",content[@"addr"]];
    //3.给查询请求设置谓词
    request.predicate = predicate;
    //4.查询数据
    NSArray<Wallet*> *arr = [kCoreDataManager.persistentContainer.viewContext executeFetchRequest:request error:nil];
    
    NSString *strName = content[@"name"];
    if (strName == nil || strName.length < 1) {
        // 命名为空
        NSDictionary *result = [self dictionaryResult:@"0" withMsg:@"请重新输入名字"];
        if (replyHandler) replyHandler(result);
        return;
    }
    if (arr.count >= 0) {
        // 修改钱包
        for (Wallet *wallet in arr) {
            wallet.name = content[@"name"];
        }
        [kCoreDataManager save];
        [self reloadData];
        NSDictionary *result = [self dictionaryResult:@"1" withMsg:@"钱包名称已更改"];
        if (replyHandler) replyHandler(result);
        return;
    }else{
        // 不存在此钱包
        NSDictionary *result = [self dictionaryResult:@"0" withMsg:@"钱包不存在"];
        if (replyHandler) replyHandler(result);
    }
    
}

// 更改钱包的头像
- (void)changeWalletHeadImgWithMessage:(nonnull NSDictionary<NSString *,id> *)message replyHandler:(nonnull void (^)(NSDictionary<NSString *,id> * _Nonnull))replyHandler{
    NSFetchRequest *request = [Wallet fetchRequest];
    NSDictionary *content = message[@"content"];
    if (content[@"avatar"] == nil || [content[@"avatar"] isEqualToString:@""]) {
        return;
    }
    //2.创建查询谓词（查询条件）
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"addr == %@",content[@"addr"]];
    //3.给查询请求设置谓词
    request.predicate = predicate;
    //4.查询数据
    NSArray<Wallet*> *arr = [kCoreDataManager.persistentContainer.viewContext executeFetchRequest:request error:nil];
    
    if (arr.count >= 0) {
        // 修改钱包
        for (Wallet *wallet in arr) {
            wallet.avatar = content[@"avatar"];
        }
        [kCoreDataManager save];
        [self reloadData];
        NSDictionary *result = [self dictionaryResult:@"1" withMsg:@"钱包头像已更改"];
        if (replyHandler) replyHandler(result);
        return;
    }else{
        // 不存在此钱包
        NSDictionary *result = [self dictionaryResult:@"0" withMsg:@"钱包不存在"];
        if (replyHandler) replyHandler(result);
    }
    
}

@end



